package com.example.demo;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author libo
 * @ClassName TestString
 * @date 2019/2/26 15:42
 */
public class TestString {
    public static void main(String[] args) {
        String s = "eabadf";
        System.out.println(longestPalindrome(s));
    }

    public static  int lengthOfLongestSubstring(String s) {
            int n = s.length();
            int ans =0,i = 0,j =0;
            Set<Character> set = new HashSet<>();
            while (i < n && j < n){
                    if(!set.contains(s.charAt(j))){
                        set.add(s.charAt(j++));
                        ans = Math.max(ans,j-i);
                    }else{
                        set.remove(s.charAt(i++));
                    }
            }
            return  ans;
    }

    public static  int lengthOfLongestSubstring2(String s) {
        int n = s.length(), ans = 0;
        Map<Character, Integer> map = new HashMap<>(); // current index of character
        // try to extend the range [i, j]
        for (int j = 0, i = 0; j < n; j++) {
            if (map.containsKey(s.charAt(j))) {
                i = Math.max(map.get(s.charAt(j)), i);
            }
            ans = Math.max(ans, j - i + 1);
            map.put(s.charAt(j), j + 1);
        }
        return ans;
    }

  public static String longestPalindrome(String s){
        if(s == null || s.length() < 1){
             return  "";
        }
        int start = 0,end = 0;
      for (int i = 0; i < s.length() ; i++) {
          int  len1 = expandAroundCenter(s,i,i);
          int  len2 = expandAroundCenter(s,i,i+1);
          int  len = Math.max(len1,len2);
          if(len > end - start){
              start = i-(len-1)/2;
              end = i + len/2;
          }
      }
      return  s.substring(start,end+1);

  }
  private static int expandAroundCenter(String s,int left,int right){
        int L = left, R  = right;
        while (L >=0 && R < s.length()-1 && s.charAt(L) == s.charAt(R)){
            L --;
            R ++;
        }
        return  R - L -1;
  }

}
